const router = require('koa-router')()
router.prefix('/dic')

const cfg = require('../config')
let sqlserver = require('mssql');
let dbConfigSource = {
    server: cfg.dicServer,
    database: 'MR_FS_DB',
    user: cfg.dicServerUser,
    password: cfg.dicServerPassword,
    port: 1433
};
let dbsecurityConfigSource = {
    server: cfg.dicServer,
    database: 'SecurityDB',
    user: cfg.dicServerUser,
    password: cfg.dicServerPassword,
    port: 1433
};
// let con = undefined
// async function getConnection() {
//     if (con == undefined)

//         con = await sqlserver.connect(dbConfigSource);
//     return con
// }
async function executeSql(strsql, dbconfig) {


    try {
        console.log(strsql);
        //let pool = await getConnection()
        var pool = new sqlserver.ConnectionPool(dbconfig);
        await pool.connect();
        let request = pool.request();
        request.multiple = true;
        let result = await request.query(strsql);

        // console.log(pool);
        // return []
        //let r = await pool.request().query(strsql).recordset;
        console.log('query finished');
        console.log(result.recordset);
        return result.recordset
    } catch (error) {
        console.log(error);
    } finally {
        //await doRelease(pool);
        await sqlserver.close();
    }
}

function parseUrl(url) {

    let obj = {}
    let ind = url.indexOf('?')
    let u = decodeURI(url.substring(ind + 1))
    let arr = u.split('&')

    arr.forEach((e, i) => {
        let nameseperatepos = e.indexOf('=')
        let name = e.substr(0, nameseperatepos)
        let value = e.substr(nameseperatepos + 1, e.length - nameseperatepos - 1)
        obj[name] = (value)
    });

    return obj
}

function getdb(s) {
    console.log(s)
    if (s == undefined || s == '') {
        console.log('default')
        return dbConfigSource
    }
    if (s === 'SecurityDB') {
        console.log('security')
        return dbsecurityConfigSource
    }
    return undefined
}
router.get('/', async (ctx, next) => {
    //parameter dictable&diccolumns
    let request = ctx.request


    let p = parseUrl(ctx.request.url)
    console.log("parse finished");
    console.log(p);
    try {
        var r = []
        if (p['dictable'] !== undefined) {
            var sql = "select " + p['diccolumns'] + " from " + p['dictable']
            console.log(sql);
            let db = getdb(p['db'])

            r = await executeSql(sql, db)
            console.log(r);
        }
        ctx.body = {
            title: 'Success!',
            body: r
        }
    } catch (err) {
        console.log(err);
    }
})

module.exports = router